import React, { useState } from 'react'
import { Card, Form, Input, Select, Switch, Button, message, Tabs, Upload, Avatar, Divider, Space, InputNumber } from 'antd'
import { UploadOutlined, UserOutlined, SaveOutlined, ReloadOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'

const { TabPane } = Tabs
const { TextArea } = Input
const { Option } = Select

export default function Settings() {
  const [loading, setLoading] = useState(false)
  const [systemForm] = Form.useForm()
  const [profileForm] = Form.useForm()
  const [securityForm] = Form.useForm()

  const [systemSettings, setSystemSettings] = useState({
    systemName: '智慧园区管理系统',
    systemVersion: '1.0.0',
    companyName: '智慧科技有限公司',
    contactEmail: 'admin@smartpark.com',
    contactPhone: '400-123-4567',
    address: '北京市朝阳区科技园区',
    timezone: 'Asia/Shanghai',
    language: 'zh-CN',
    theme: 'light',
    autoBackup: true,
    backupInterval: 24,
    logRetention: 30,
    sessionTimeout: 30
  })

  const [userProfile, setUserProfile] = useState({
    username: 'admin',
    email: 'admin@smartpark.com',
    phone: '13800138000',
    department: '技术部',
    role: 'admin',
    avatar: '',
    description: '系统管理员'
  })

  const [securitySettings, setSecuritySettings] = useState({
    passwordPolicy: {
      minLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true
    },
    loginSecurity: {
      maxAttempts: 5,
      lockoutDuration: 30,
      twoFactorAuth: false,
      sessionTimeout: 30
    },
    accessControl: {
      ipWhitelist: '',
      allowMultipleLogin: false,
      forcePasswordChange: 90
    }
  })

  const handleSystemSave = async (values) => {
    setLoading(true)
    try {
      setSystemSettings({ ...systemSettings, ...values })
      message.success('系统设置保存成功')
    } catch (error) {
      message.error('保存失败')
    } finally {
      setLoading(false)
    }
  }

  const handleProfileSave = async (values) => {
    setLoading(true)
    try {
      setUserProfile({ ...userProfile, ...values })
      message.success('个人信息保存成功')
    } catch (error) {
      message.error('保存失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSecuritySave = async (values) => {
    setLoading(true)
    try {
      setSecuritySettings({ ...securitySettings, ...values })
      message.success('安全设置保存成功')
    } catch (error) {
      message.error('保存失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSystemReset = () => {
    systemForm.resetFields()
    message.info('已重置为默认值')
  }

  const uploadProps = {
    name: 'file',
    action: '/api/upload/avatar',
    listType: 'picture-card',
    maxCount: 1,
    onChange(info) {
      if (info.file.status === 'done') {
        message.success('头像上传成功')
        setUserProfile(prev => ({ ...prev, avatar: info.file.response.url }))
      } else if (info.file.status === 'error') {
        message.error('头像上传失败')
      }
    },
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card title="系统设置">
          <Tabs defaultActiveKey="system">
            <TabPane tab="系统配置" key="system">
              <Form
                form={systemForm}
                layout="vertical"
                initialValues={systemSettings}
                onFinish={handleSystemSave}
              >
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
                  <div>
                    <h4>基本信息</h4>
                    <Form.Item name="systemName" label="系统名称" rules={[{ required: true }]}>
                      <Input placeholder="请输入系统名称" />
                    </Form.Item>
                    <Form.Item name="systemVersion" label="系统版本">
                      <Input placeholder="请输入系统版本" disabled />
                    </Form.Item>
                    <Form.Item name="companyName" label="公司名称" rules={[{ required: true }]}>
                      <Input placeholder="请输入公司名称" />
                    </Form.Item>
                    <Form.Item name="contactEmail" label="联系邮箱" rules={[{ required: true, type: 'email' }]}>
                      <Input placeholder="请输入联系邮箱" />
                    </Form.Item>
                    <Form.Item name="contactPhone" label="联系电话">
                      <Input placeholder="请输入联系电话" />
                    </Form.Item>
                    <Form.Item name="address" label="公司地址">
                      <TextArea rows={3} placeholder="请输入公司地址" />
                    </Form.Item>
                  </div>

                  <div>
                    <h4>系统配置</h4>
                    <Form.Item name="timezone" label="时区" rules={[{ required: true }]}>
                      <Select placeholder="请选择时区">
                        <Option value="Asia/Shanghai">Asia/Shanghai (UTC+8)</Option>
                        <Option value="Asia/Tokyo">Asia/Tokyo (UTC+9)</Option>
                        <Option value="America/New_York">America/New_York (UTC-5)</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item name="language" label="语言" rules={[{ required: true }]}>
                      <Select placeholder="请选择语言">
                        <Option value="zh-CN">简体中文</Option>
                        <Option value="en-US">English</Option>
                        <Option value="ja-JP">日本語</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item name="theme" label="主题">
                      <Select placeholder="请选择主题">
                        <Option value="light">浅色主题</Option>
                        <Option value="dark">深色主题</Option>
                        <Option value="auto">跟随系统</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item name="autoBackup" label="自动备份" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name="backupInterval" label="备份间隔(小时)">
                      <InputNumber min={1} max={168} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="logRetention" label="日志保留天数">
                      <InputNumber min={1} max={365} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="sessionTimeout" label="会话超时(分钟)">
                      <InputNumber min={5} max={480} style={{ width: '100%' }} />
                    </Form.Item>
                  </div>
                </div>

                <Divider />
                <Space>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={loading}
                    icon={<SaveOutlined />}
                  >
                    保存设置
                  </Button>
                  <Button 
                    onClick={handleSystemReset}
                    icon={<ReloadOutlined />}
                  >
                    重置
                  </Button>
                </Space>
              </Form>
            </TabPane>

            <TabPane tab="个人资料" key="profile">
              <Form
                form={profileForm}
                layout="vertical"
                initialValues={userProfile}
                onFinish={handleProfileSave}
              >
                <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr', gap: 24 }}>
                  <div>
                    <h4>头像</h4>
                    <div style={{ textAlign: 'center' }}>
                      <Avatar 
                        size={120} 
                        icon={<UserOutlined />}
                        src={userProfile.avatar}
                        style={{ marginBottom: 16 }}
                      />
                      <Upload {...uploadProps}>
                        <Button icon={<UploadOutlined />}>上传头像</Button>
                      </Upload>
                    </div>
                  </div>

                  <div>
                    <h4>基本信息</h4>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                      <Form.Item name="username" label="用户名" rules={[{ required: true }]}>
                        <Input placeholder="请输入用户名" />
                      </Form.Item>
                      <Form.Item name="email" label="邮箱" rules={[{ required: true, type: 'email' }]}>
                        <Input placeholder="请输入邮箱" />
                      </Form.Item>
                      <Form.Item name="phone" label="手机号">
                        <Input placeholder="请输入手机号" />
                      </Form.Item>
                      <Form.Item name="department" label="部门">
                        <Select placeholder="请选择部门">
                          <Option value="技术部">技术部</Option>
                          <Option value="市场部">市场部</Option>
                          <Option value="财务部">财务部</Option>
                          <Option value="人事部">人事部</Option>
                        </Select>
                      </Form.Item>
                      <Form.Item name="role" label="角色">
                        <Select placeholder="请选择角色" disabled>
                          <Option value="admin">管理员</Option>
                          <Option value="manager">经理</Option>
                          <Option value="employee">员工</Option>
                        </Select>
                      </Form.Item>
                    </div>
                    <Form.Item name="description" label="个人描述">
                      <TextArea rows={4} placeholder="请输入个人描述" />
                    </Form.Item>
                  </div>
                </div>

                <Divider />
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<SaveOutlined />}
                >
                  保存资料
                </Button>
              </Form>
            </TabPane>

            <TabPane tab="安全设置" key="security">
              <Form
                form={securityForm}
                layout="vertical"
                initialValues={securitySettings}
                onFinish={handleSecuritySave}
              >
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24 }}>
                  <div>
                    <h4>密码策略</h4>
                    <Form.Item name={['passwordPolicy', 'minLength']} label="最小长度">
                      <InputNumber min={6} max={20} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name={['passwordPolicy', 'requireUppercase']} label="需要大写字母" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name={['passwordPolicy', 'requireLowercase']} label="需要小写字母" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name={['passwordPolicy', 'requireNumbers']} label="需要数字" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name={['passwordPolicy', 'requireSpecialChars']} label="需要特殊字符" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                  </div>

                  <div>
                    <h4>登录安全</h4>
                    <Form.Item name={['loginSecurity', 'maxAttempts']} label="最大尝试次数">
                      <InputNumber min={3} max={10} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name={['loginSecurity', 'lockoutDuration']} label="锁定时长(分钟)">
                      <InputNumber min={5} max={120} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name={['loginSecurity', 'twoFactorAuth']} label="双因子认证" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name={['loginSecurity', 'sessionTimeout']} label="会话超时(分钟)">
                      <InputNumber min={5} max={480} style={{ width: '100%' }} />
                    </Form.Item>
                  </div>

                  <div>
                    <h4>访问控制</h4>
                    <Form.Item name={['accessControl', 'ipWhitelist']} label="IP白名单">
                      <TextArea rows={4} placeholder="每行一个IP地址" />
                    </Form.Item>
                    <Form.Item name={['accessControl', 'allowMultipleLogin']} label="允许多地登录" valuePropName="checked">
                      <Switch />
                    </Form.Item>
                    <Form.Item name={['accessControl', 'forcePasswordChange']} label="强制密码更换(天)">
                      <InputNumber min={30} max={365} style={{ width: '100%' }} />
                    </Form.Item>
                  </div>
                </div>

                <Divider />
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<SaveOutlined />}
                >
                  保存设置
                </Button>
              </Form>
            </TabPane>
          </Tabs>
        </Card>
      </div>
    </Layout>
  )
}



